# -*- coding: utf-8 -*-
'''提取视频中的视频'''
from tkinter import *
from tkinter import ttk
from tkinter.ttk import *
import tkinter.messagebox
import tkinter as tk
from tkinter import filedialog
from media import basic
import os
import subprocess
import re
from media import mediaUtil
import threading

class anFrame(object):
    def __init__(self,parent):
        self.root = tkinter.Toplevel(parent)
        self.root.title('视频提取')
         #子窗口随着主窗口关闭或最小化
        self.root.transient(parent)
        self.root.resizable(False, False)
        self.root.minsize(500, 155)
        self.centerWin(self.root,500, 155)
        
        anFrame = ttk.Frame(self.root)
        bm = PhotoImage(file = mediaUtil.SOURCE_PATH+'video.png')
        tipLabel = Label(anFrame,image=bm)
        tipLabel.bm = bm
        tipLabel.grid(row=0,rowspan=6,column=0,padx=5,pady=5,sticky=(N, W, E, S))
        
        videoLabel = Label(anFrame,text='视频文件：')
        videoLabel.grid(column=1, row=2,padx=3,sticky=(N, W, E, S))
        self.videoString = StringVar()
        self.videoPath = Entry(anFrame,textvariable = self.videoString,width=30,state=DISABLED)
        self.videoPath.grid(column=2, row=2,padx=3,sticky=(W, E))
        videoPathBtn = ttk.Button(anFrame,text="选择文件",width=10,command=self.getVideoPath).grid(row=2,column=3,sticky=W+E,padx=10)
        
        outLabel = Label(anFrame,text='存放文件夹：')
        outLabel.grid(column=1, row=3,padx=3,sticky=(N, W, E, S))
        self.video2String = StringVar()
        self.video2Path = Entry(anFrame,textvariable = self.video2String,width=30,state=DISABLED)
        self.video2Path.grid(column=2, row=3,padx=3,sticky=(W, E))
        audioPathBtn = ttk.Button(anFrame,text="选择文件夹",width=10,command=self.getVideo2Path).grid(row=3,column=3,sticky=W+E,padx=10)

        self.execBtn = ttk.Button(anFrame,text="提取",width=10,command=self.getVideoAn)
        self.execBtn.grid(row=7,column=3,sticky=W+E,padx=10)
        
        anFrame.grid(row=0,column=0,pady=5,sticky=(N, W, E, S))
        self.statusLabel = Label(anFrame,text='已就绪',relief=GROOVE,anchor=W)
        self.statusLabel.grid(row=8,column=0,columnspan=4,pady=5,sticky=(N, W, E, S))
    
    '''窗口居中'''
    def centerWin(self,root,width,height):
        screenwidth = root.winfo_screenwidth()
        screenheight = root.winfo_screenheight()
        size = '%dx%d+%d+%d' % (width, height, (screenwidth - width)/2, (screenheight - height)/2)  
        root.geometry(size)
    
    '''获取视频文件地址'''
    def getVideoPath(self):
        self.videoString.set('')
        path = filedialog.askopenfilename()
        if path !="":
            ext = os.path.splitext(path)[1][1:]
            isVideo = 0
            for et in basic.VIDEOS:
                if et == ext:
                    isVideo = 1
            if isVideo == 1:
                self.videoString.set(path)
            else:
                tkinter.messagebox.showerror("提示","请选择视频文件")
        
    '''获取视频提取的存放路径'''
    def getVideo2Path(self):
        path = filedialog.askdirectory()
        if path !="":
            self.video2String.set(path)
    
    '''提取视频中的音频'''
    def getVideoAn(self):
        try:
            videoPath = self.videoString.get()
            if videoPath == "":
                tkinter.messagebox.showerror("提示","请选择视频文件")
                return False
            video2Path = self.video2String.get()
            if video2Path =="":
                tkinter.messagebox.showerror("提示","请选择存放文件夹")
                return False
            self.statusLabel['text']='提取中'
            videoName = os.path.basename(videoPath)
            ret = list(re.finditer('\.', videoName))
            videoName = videoName[0:ret[-1].span()[0]]
            ext = os.path.splitext(videoPath)[1][1:]
            outputFile = video2Path+'/{0}.{1}'.format(videoName,ext)
            
            cmd = mediaUtil.cmd_mediaInfo(videoPath)
            subprocess.call(cmd)
            result = subprocess.getoutput(cmd)
            b = re.search(r'bitrate: (\d+) kb', result)
            #获取原视频的比特率
            bitrate = b.group(1)
            #获取提交音频命令
            cmd = mediaUtil.cmd_getVideoAn(videoPath, outputFile,bitrate)
            if cmd == None:
                tkinter.messagebox.showerror("提示","无法获取视频提取命令")
                return Flase
            #执行提取音频命令
            subprocess.Popen(cmd)
            #禁用提取按钮
            self.execBtn.config(state=DISABLED)
            #获取提取进度
            vn_thread = threading.Thread(target=self.getAnProgress,args=(None,cmd))
            vn_thread.start()
        except:
            self.statusLabel['text']='提取失败'
    
    '''获取提取进度'''
    def getAnProgress(self,x,cmd):
        try:
            iscomplete = 0
            while iscomplete ==0:
                info = mediaUtil.getCmdExecInfo(cmd)
                if info !="":
                    iscomplete=1
            if iscomplete ==1:
                self.statusLabel['text']='提取成功'
            #启用提取按钮
            self.execBtn.config(state=NORMAL)
        except:
            self.statusLabel['text']='提取失败'
